//
//  MLStage1.m
//  WaterProof
//
//  Created by victor0321 on 12/1/3.
//  Copyright 2012年 __MyCompanyName__. All rights reserved.
//

#import "MLGrid.h"
#import "SimpleAudioEngine.h"
@interface MLGrid()
-(void) initGrid;
-(void) startCheckRoute;
-(void) setBucketImage:(int) bucketTag locaitonx:(int) x locationx:(int)y;
@end
void checkNext(int row,int column,int dir,int idx, int pipeLocation[][GRID_MAX_WIDTH],
               int pipeRoute[][GRID_MAX_WIDTH]);
void checkPipe(int pipeLocaiton[][GRID_MAX_WIDTH], int pipeRoute[][GRID_MAX_WIDTH]);
void setBucket(int bucketNumber, int x, int y);
@implementation MLGrid

-(void) setBucketImage:(int) bucketTag locaitonx:(int) x locationx:(int)y{
    [[SimpleAudioEngine sharedEngine] playEffect:@"setBucket.caf"]; 
    switch (bucketTag) {
            CCLOG(@"QQQQQQQQQQQQQQQQQ");
        case pailsmall:
            [bucketBack[x][y] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"SBucketEmptyBut.png"]];
            [bucketFront[x][y] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"SBucketEmptyTopMask.png"]]; 
            [bucketBack[x-1][y] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"SBucketEmptyTop.png"]]; 
            
            [bucketBack[x-1][y] setVisible:true];
            [bucketBack[x][y] setVisible:true];
            [bucketFront[x][y] setVisible:true];
            bucketSize[y] = pailsmall;
            break;
        case pailmiddle:
            [bucketFront[x][y] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"MBucketEmptyBut.png"]];
            [bucketFront[x-1][y] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"MBucketEmptyTopMask.png"]]; 
            [bucketBack[x-1][y] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"MBucketEmptyTop.png"]];   
            
            [bucketBack[x-1][y] setVisible:true];
            [bucketFront[x-1][y] setVisible:true];
            [bucketFront[x][y] setVisible:true];
            bucketSize[y] = pailmiddle;
            break;
        case pailbig:
            [bucketFront[x][y] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"LBucketEmptyBut.png"]];
            [bucketFront[x-1][y] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"LBucketEmptyTopMask.png"]]; 
            [bucketBack[x-1][y] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"LBucketEmptyTop.png"]];    
            [bucketBack[x-1][y] setVisible:true];
            [bucketFront[x-1][y] setVisible:true];
            [bucketFront[x][y] setVisible:true];
            bucketSize[y] = pailbig;
            break;
        default:
            break;
    }

    hasBucket[x-1][y] = true;
    hasBucket[x][y] = true;
}
-(void) setBucketWaterFullImage:(int)bucketTag locaitonx:(int)x{
    switch (bucketTag) {
        case pailsmall:
            [bucketBack[GRID_MAX_HEIGHT-1][x] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"SBucketFullBut.png"]];
            [bucketFront[GRID_MAX_HEIGHT-1][x] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"SBucketEmptyTopMask.png"]]; 
            [bucketBack[GRID_MAX_HEIGHT-1-1][x] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"SBucketEmptyTop.png"]]; 
            
            [bucketBack[GRID_MAX_HEIGHT-1-1][x]  setVisible:true];
            [bucketBack[GRID_MAX_HEIGHT-1][x] setVisible:true];
            [bucketFront[GRID_MAX_HEIGHT-1][x] setVisible:true];
            break;
        case pailmiddle:
            [bucketFront[GRID_MAX_HEIGHT-1][x] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"MBucketEmptyBut.png"]];
            [bucketFront[GRID_MAX_HEIGHT-1-1][x] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"MBucketEmptyTopMask.png"]]; 
            [bucketBack[GRID_MAX_HEIGHT-1-1][x] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"MBucketFullTop.png"]];   
            
            [bucketBack[GRID_MAX_HEIGHT-1-1][x] setVisible:true];
            [bucketFront[GRID_MAX_HEIGHT-1-1][x] setVisible:true];
            [bucketFront[GRID_MAX_HEIGHT-1][x] setVisible:true];
            break;
        case pailbig:
            [bucketFront[GRID_MAX_HEIGHT-1][x] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"LBucketEmptyBut.png"]];
            [bucketFront[GRID_MAX_HEIGHT-1-1][x] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"LBucketEmptyTopMask.png"]]; 
            [bucketBack[GRID_MAX_HEIGHT-1-1][x] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"LBucketFullTop.png"]];    
            [bucketBack[GRID_MAX_HEIGHT-1-1][x] setVisible:true];
            [bucketFront[GRID_MAX_HEIGHT-1-1][x] setVisible:true];
            [bucketFront[GRID_MAX_HEIGHT-1][x] setVisible:true];
            break;
        default:
            break;
    }
}

-(bool) setGridImage:(int) imageTag location:(CGPoint)position
{
    //CCLOG(@"weapon = %i",imageTag);
    if (position.y < BOTTOM_DISTANCE) {
        return false;
    }
    int rowIdx = GRID_MAX_HEIGHT - (int)(position.y-BOTTOM_DISTANCE)/128 - 1;
    int colIdx = position.x/128;

    if(pipeLocation[rowIdx][colIdx] != 0 ){ return false;}
 
    switch (imageTag) {
        case pipeA:
            [grid[rowIdx][colIdx] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"tube1.png"]];
            [[SimpleAudioEngine sharedEngine] playEffect:@"setPipe.caf"];
            break;
        case pipeB:
            [grid[rowIdx][colIdx] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"tube2.png"]];    
            [[SimpleAudioEngine sharedEngine] playEffect:@"setPipe.caf"];
            break;
        case pipeC:
            [grid[rowIdx][colIdx] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"tube5.png"]];    
            [[SimpleAudioEngine sharedEngine] playEffect:@"setPipe.caf"];
            break;
        case pipeD:
            [grid[rowIdx][colIdx] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"tube6.png"]];  
            [[SimpleAudioEngine sharedEngine] playEffect:@"setPipe.caf"];
            break;
        case pipeE:
            [grid[rowIdx][colIdx] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"tube3.png"]];  
            [[SimpleAudioEngine sharedEngine] playEffect:@"setPipe.caf"];
            break;
        case pipeF:
            [grid[rowIdx][colIdx] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"tube4.png"]];    
            [[SimpleAudioEngine sharedEngine] playEffect:@"setPipe.caf"];
            break;
        case pailsmall:
            if (rowIdx != GRID_MAX_HEIGHT-1) return false;
            if (colIdx == 3 || colIdx == 4 || colIdx == 5) return false;
            if (hasBucket[rowIdx][colIdx] == TRUE) return false;
            //CCLOG(@"eat shit");
            [self setBucketImage:pailsmall locaitonx:rowIdx locationx:colIdx];
            return true;
            break;
        case pailmiddle:
            if (rowIdx != GRID_MAX_HEIGHT-1) return false;
            if (colIdx == 3 || colIdx == 4 || colIdx == 5) return false;
            if (hasBucket[rowIdx][colIdx] == TRUE) return false;
            [self setBucketImage:pailmiddle locaitonx:rowIdx locationx:colIdx];
            return true;
            break;
        case pailbig:
            if (rowIdx != GRID_MAX_HEIGHT-1) return false;
            if (colIdx == 3 || colIdx == 4 || colIdx == 5) return false;
            if (hasBucket[rowIdx][colIdx] == TRUE) return false;
            [self setBucketImage:pailbig locaitonx:rowIdx locationx:colIdx];
            return true;
            break;
        default:
            [grid[rowIdx][colIdx] setTexture:[[CCTextureCache sharedTextureCache] addImage:@"tube1.png"]];            
            break;
    }
    
    pipeLocation[rowIdx][colIdx] = imageTag;
    return true;
}

-(void) showGrid{
    for (int i = 0; i < GRID_MAX_HEIGHT ; i++ )
    {
        for (int j = 0; j < GRID_MAX_WIDTH; j++)
        {
            [grid[i][j] setVisible:true];
        }
    }
}
-(void) hiddenGrid{
    for (int i = 0; i < GRID_MAX_HEIGHT ; i++ )
    {
        for (int j = 0; j < GRID_MAX_WIDTH; j++)
        {
            if( pipeLocation[i][j] == 0 ) [grid[i][j] setVisible:false];
        }
    }
}
-(id) init
{
	if ((self = [super init]))
	{
        [self initGrid];
        
	}
	return self;
}

-(void) registerWithTouchDispatcher{
	[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:1 swallowsTouches:YES];
}

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    
    return YES;
}

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    
}

-(void) initGrid
{
    soundState = [CCSprite spriteWithFile:@"SoundBad.png"];
    soundState.position = CGPointMake(130, 300);
    soundState.tag = 4;
    [soundState setVisible:false];
    
    [self addChild:soundState z:-3];
    
    // initialize matrix
    for(int i = 0;i < GRID_MAX_HEIGHT; i++ )
    {
        for( int j = 0; j < GRID_MAX_WIDTH; j++ )
        {
            pipeLocation[i][j] = 0;
            pipeRoute[i][j] = 0;
            pipeTerminalDir[i][j] = 0;
            isWatterEmmiter[i][j] = false;
            waterEmmiterTag[i][j] = WATERTAGOFFSET+i*GRID_MAX_WIDTH+j;
            hasBucket[i][j] = false;
        }
    }
    srand(time(NULL));
    int leakNum = 0;
    for(int i = 0;i < GRID_MAX_WIDTH; i++ )
    {
        pipeTerminalTop[i] = 0;
        isWatterEmmiterTop[i] = false;
        waterEmmiterTopTag[i] = WATERTAGOFFSET+GRID_MAX_WIDTH*GRID_MAX_HEIGHT+i;
        bucketWaterNumber[i] = 0;
        bucketSize[i] = 0;
        leakWaterFlag[i] = false;
        
        int ramNum = (rand()%2);
        
        if (leakNum < 6){
            if (ramNum) {
                leakWaterLocation[i] = false;
            }else{
                leakWaterLocation[i] = true;
                leakNum = leakNum+1;
            }
        }
        
    }
    
    MLGridFloorKickNum = 0;
    
    //rectArray = [[NSMutableArray alloc] init];
    CGFloat height = [UIScreen mainScreen].bounds.size.width;
    CGFloat width = [UIScreen mainScreen].bounds.size.height;
    CGFloat disBetweenRectX = (width-RECTSIZE*GRID_MAX_WIDTH)/(GRID_MAX_WIDTH +1);
    CGFloat disBetweenRectY = (height-RECTSIZE*GRID_MAX_HEIGHT-BOTTOM_DISTANCE)/(GRID_MAX_HEIGHT +1);
    CGFloat startPointX = disBetweenRectX+RECTSIZE/2;
    CGFloat startPointY = BOTTOM_DISTANCE+RECTSIZE/2;
    for (int i = 0; i < GRID_MAX_HEIGHT ; i++ )
    {
        for (int j = 0; j < GRID_MAX_WIDTH; j++)
        {
            //rectObject = [[RectObject alloc] init];
            CGFloat xPosition = startPointX + j*(RECTSIZE+disBetweenRectX);
            CGFloat yPosition = startPointY + i*(RECTSIZE+disBetweenRectY);
            grid[GRID_MAX_HEIGHT-i-1][j] = [CCSprite spriteWithFile:@"grid2.png"];
            grid[GRID_MAX_HEIGHT-i-1][j].position = CGPointMake(xPosition, yPosition);
            grid[GRID_MAX_HEIGHT-i-1][j].tag = 4;
            [grid[GRID_MAX_HEIGHT-i-1][j] setVisible:false];
            
            [self addChild:grid[GRID_MAX_HEIGHT-i-1][j] z:pipe_order];
           // [rectObject setX:xPosition];
           // [rectObject setY:yPosition];
           // [rectObject setIndex:GRID_MAX_WIDTH*(GRID_MAX_HEIGHT-i-1) +j];
           // [rectObject setImageTag:0];
           // [rectArray addObject:rectObject];
           // [rectObject release];
        }
    }
    for (int i = 0; i < GRID_MAX_HEIGHT; i++) {
        for (int j=0; j<GRID_MAX_WIDTH; j++) {
         //   rectObject = [[RectObject alloc] init];
            CGFloat xPosition = startPointX + j*(RECTSIZE+disBetweenRectX);
            CGFloat yPosition = startPointY + i*(RECTSIZE+disBetweenRectY);
            bucketFront[GRID_MAX_HEIGHT-i-1][j] = [CCSprite spriteWithFile:@"grid2.png"];
            bucketFront[GRID_MAX_HEIGHT-i-1][j].position = CGPointMake(xPosition, yPosition);
            bucketFront[GRID_MAX_HEIGHT-i-1][j].tag = 4;
            [bucketFront[GRID_MAX_HEIGHT-i-1][j] setVisible:false];
            
            [self addChild:bucketFront[GRID_MAX_HEIGHT-i-1][j] z:bucket_front];
         //   [rectObject setX:xPosition];
         //   [rectObject setY:yPosition];
         //   [rectObject setIndex:GRID_MAX_WIDTH*(GRID_MAX_HEIGHT-i-1) +j];
         //   [rectObject setImageTag:0];
         //   [rectArray addObject:rectObject];
         //   [rectObject release];            
            
            //bucketFront[i][j] = 
        }
    }
    for (int i = 0; i < GRID_MAX_HEIGHT; i++) {
        for (int j=0; j<GRID_MAX_WIDTH; j++) {
            //   rectObject = [[RectObject alloc] init];
            CGFloat xPosition = startPointX + j*(RECTSIZE+disBetweenRectX);
            CGFloat yPosition = startPointY + i*(RECTSIZE+disBetweenRectY);
            bucketBack[GRID_MAX_HEIGHT-i-1][j] = [CCSprite spriteWithFile:@"grid2.png"];
            bucketBack[GRID_MAX_HEIGHT-i-1][j].position = CGPointMake(xPosition, yPosition);
            bucketBack[GRID_MAX_HEIGHT-i-1][j].tag = 4;
            [bucketBack[GRID_MAX_HEIGHT-i-1][j] setVisible:false];
            
            [self addChild:bucketBack[GRID_MAX_HEIGHT-i-1][j] z:bucket_back];
            //   [rectObject setX:xPosition];
            //   [rectObject setY:yPosition];
            //   [rectObject setIndex:GRID_MAX_WIDTH*(GRID_MAX_HEIGHT-i-1) +j];
            //   [rectObject setImageTag:0];
            //   [rectArray addObject:rectObject];
            //   [rectObject release];            
            
            //bucketFront[i][j] = 
        }
    }
    CCLOG(@"initGrid finish");
}
void checkNext(int row,int column,int dir,int idx, int pipeLocation[][GRID_MAX_WIDTH],
               int pipeRoute[][GRID_MAX_WIDTH]){
    if( dir == left ){
        if (column - 1 < 0) {
            return;
        }
        if (pipeLocation[row][column-1] == pipeB){ checkNext(row, column-1, left, idx,pipeLocation,pipeRoute);}
        else if (pipeLocation[row][column-1] == pipeC){ checkNext(row, column-1, up, idx,pipeLocation,pipeRoute);}
        else if (pipeLocation[row][column-1] == pipeF){ checkNext(row, column-1, down, idx,pipeLocation,pipeRoute);}
        else{
            //terminal case
            pipeTerminalDir[row][column-1] = right;
        }
        pipeRoute[row][column-1] = idx;
        
    }else if (dir == up){
        if (row - 1 < 0){
            pipeTerminalTop[column] = down;
            return;
        }
        if (pipeLocation[row-1][column] == pipeA){ checkNext(row-1, column, up, idx,pipeLocation,pipeRoute);}
        else if (pipeLocation[row-1][column] == pipeE){ checkNext(row-1, column, left, idx,pipeLocation,pipeRoute);}
        else if (pipeLocation[row-1][column] == pipeF){ checkNext(row-1, column, right, idx,pipeLocation,pipeRoute);}
        else{
            //terminal case
            pipeTerminalDir[row-1][column] = down;
        }
        pipeRoute[row-1][column] = idx;
    }else if (dir == right){
        if (column + 1 > GRID_MAX_WIDTH-1){
            return;
        }
        if (pipeLocation[row][column+1] == pipeB){ checkNext(row, column+1, right, idx,pipeLocation,pipeRoute);}
        else if (pipeLocation[row][column+1] == pipeD){ checkNext(row, column+1, up, idx,pipeLocation,pipeRoute);}
        else if (pipeLocation[row][column+1] == pipeE){ checkNext(row, column+1, down, idx,pipeLocation,pipeRoute);}
        else{
            //terminal case
            pipeTerminalDir[row][column+1] = left;
        }
        pipeRoute[row][column+1] = idx;
    }else{
        if (row + 1 > GRID_MAX_HEIGHT -1) {
            return;
        }
        if (pipeLocation[row+1][column] == pipeA){ checkNext(row+1, column, down, idx,pipeLocation,pipeRoute);}
        else if (pipeLocation[row+1][column] == pipeC){ checkNext(row+1, column, right, idx,pipeLocation,pipeRoute);}
        else if (pipeLocation[row+1][column] == pipeD){ checkNext(row+1, column, left, idx,pipeLocation,pipeRoute);}
        else{
            //terminal case
            pipeTerminalDir[row+1][column] = up;
        }
        pipeRoute[row+1][column] = idx;
    }
}
-(void) startCheckRoute{
    checkPipe(pipeLocation, pipeRoute);
}
-(void) runLeakEffect:(NSInteger)x locationy:(NSInteger)y index1:(NSInteger)idxx emmiterTag:(NSInteger)WaterTag{
    MLMyParticleSystem* water;
    //CCLOG(@"run 2");
    if (!isWaterSoundOn) {
        waterSoundID = [[SimpleAudioEngine sharedEngine] playEffect:@"flowDown.caf" pitch:1.0 pan:0 gain:0.5 loop:true];
        isWaterSoundOn = YES;
    }
    water = [MLMyParticleSystem particleWithFile:@"waterFlowUp2.plist"];
    water.position = CGPointMake(x+64, 768);

    water.duration=-1;
    //water.totalParticles = 200;// Can change the flow of water
    //water.positionType=kCCPositionTypeGrouped;
    //checkPipe(pipeLocation, pipeRoute);
    [self addChild:water z:water_order tag:WaterTag];  
}
-(void) setWaterEffect{
    CCNode* node;
    // leak water 
    for (int i = 0; i < GRID_MAX_WIDTH; i++) {
        if(leakWaterFlag[i] == true && hasBucket[GRID_MAX_HEIGHT-1][i]==true)
        {
            node = [self getChildByTag:10000+i];
            MLMyParticleSystem* particleSystemLayer = (MLMyParticleSystem*)node;
            [particleSystemLayer setBucketParticleSystem:i];            
        }
    }
    
    // pass bucket information to particle system
    for (int i = 0; i < GRID_MAX_HEIGHT ; i++ )
    {
        for (int j = 0; j < GRID_MAX_WIDTH; j++)
        {
            if(isWatterEmmiter[i][j] == true)
            {
                for (int k = 0; k < GRID_MAX_WIDTH ; k++ )
                {
                    if(hasBucket[GRID_MAX_HEIGHT-1][k]==true)
                    {
                        node = [self getChildByTag:waterEmmiterTag[i][j]];
                        MLMyParticleSystem* particleSystemLayer = (MLMyParticleSystem*)node;
                        [particleSystemLayer setBucketParticleSystem:k];
                    }
                }
            }
        }
    }
    // grid
    for (int i = 0; i < GRID_MAX_HEIGHT ; i++ )
    {
        for (int j = 0; j < GRID_MAX_WIDTH; j++)
        {
            if (pipeTerminalDir[i][j] == 0 && isWatterEmmiter[i][j] == true) {
                isWatterEmmiter[i][j] = false;
                [self removeChildByTag:waterEmmiterTag[i][j] cleanup:true];
            }
            else if(pipeTerminalDir[i][j] != 0 && isWatterEmmiter[i][j] == false)
            {
                [self runWaterEffect:j*128 locationy:768-i*128 index1:i index2:j emmiterTag:waterEmmiterTag[i][j]];
                isWatterEmmiter[i][j] = true;
            }
        }
    }
    CCLOG(@"isWateremmiter = %i",isWatterEmmiter[1][3]);
    CCLOG(@"pipeTerminalDir = %i",pipeTerminalDir[1][3]);
    // top row outside screen
    for (int i = 0; i < GRID_MAX_WIDTH ; i++ )
    {
        if (pipeTerminalTop[i] == 0 && isWatterEmmiterTop[i]==true) {
            isWatterEmmiterTop[i]=false;
            [self removeChildByTag:waterEmmiterTopTag[i] cleanup:true];
        }
        else if(pipeTerminalTop[i] != 0 && isWatterEmmiterTop[i] == false)
        {
            //CCLOG(@"%i",i);
            [self runWaterEffect2:i*128 locationy:768 index1:i emmiterTag:waterEmmiterTopTag[i]];
            isWatterEmmiterTop[i] = true;
        }
        
        if (leakWaterFlag[i] == false && leakWaterLocation[i] == true)
        {
            leakWaterFlag[i] = true;
            [self runLeakEffect:i*128 locationy:768 index1:i emmiterTag:10000+i];
            
        }else if(leakWaterFlag[i] == true && leakWaterLocation[i] == true){
            if (pipeLocation[0][i]==pipeA || pipeLocation[0][i]==pipeC || pipeLocation[0][i]== pipeD)
            {
                leakWaterFlag[i] = false;
                [self removeChildByTag:10000+i cleanup:true];
            }
        }
    }
}
-(void) changeBucketState{
    MLGridFloorKickNum = 0;
    for (int i = 0; i< GRID_MAX_WIDTH; i++) {
        bucketWaterNumber[i] = 0;
    }
    CCNode* node;
    
    // leak water 
    for (int i = 0; i < GRID_MAX_WIDTH; i++) {
        // get water number in bucket
        node = [self getChildByTag:10000+i];
        MLMyParticleSystem* particleSystemLayer = (MLMyParticleSystem*)node;
        int waterCount;
        if(leakWaterFlag[i] == true && hasBucket[GRID_MAX_HEIGHT-1][i]==true)
        {
            waterCount = [particleSystemLayer getBucetWaterNumber:i];
            bucketWaterNumber[i] += waterCount;
        }
        // get floor kick number
        waterCount = [particleSystemLayer getfloorKickNum];
        MLGridFloorKickNum += waterCount;
        //CCLOG(@"waterCount = %i",waterCount);
    }
    // get bucket water
    for (int i = 0; i < GRID_MAX_HEIGHT ; i++ )
    {
        for (int j = 0; j < GRID_MAX_WIDTH; j++)
        {
            if(isWatterEmmiter[i][j] == true)
            {
                for (int k = 0; k < GRID_MAX_WIDTH ; k++ )
                {
                    node = [self getChildByTag:waterEmmiterTag[i][j]];
                    MLMyParticleSystem* particleSystemLayer = (MLMyParticleSystem*)node;;
                    int waterCount;
                    if(hasBucket[GRID_MAX_HEIGHT-1][k]==true)
                    {
                        waterCount = [particleSystemLayer getBucetWaterNumber:k];
                        //CCLOG(@"%i",waterCount);
                        bucketWaterNumber[k] += waterCount; 
                        //CCLOG(@"waterCount = %i",waterCount);
                    }
                    // get floor kick number
                    waterCount = [particleSystemLayer getfloorKickNum];
                    MLGridFloorKickNum += waterCount;
                    //CCLOG(@"waterCount = %i",waterCount);
                }
            }
        }
    }
    for (int i = 0; i< GRID_MAX_WIDTH; i++) {
        if(bucketWaterNumber[i] >= 1000)
        {
            [self setBucketWaterFullImage:bucketSize[i] locaitonx:i];
        }
    }
    //CCLOG(@"%i",MLGridFloorKickNum);
}
-(int) getMLGridFloorKickNum{
    return MLGridFloorKickNum;
}
-(void) runWaterEffect2:(NSInteger)x locationy:(NSInteger)y index1:(NSInteger)idxx emmiterTag:(NSInteger)WaterTag{
    MLMyParticleSystem* water;
    //CCLOG(@"run 2");
    if(pipeTerminalTop[idxx] == down){
        if (!isWaterSoundOn) {
            waterSoundID = [[SimpleAudioEngine sharedEngine] playEffect:@"flowDown.caf" pitch:1.0 pan:0 gain:0.5 loop:true];
            isWaterSoundOn = YES;
        }
        water = [MLMyParticleSystem particleWithFile:@"waterFlowDown3.plist"];
        water.position = CGPointMake(x+64, 768);
    }
    water.duration=-1;
    //water.totalParticles = 200;// Can change the flow of water
    //water.positionType=kCCPositionTypeGrouped;
    //checkPipe(pipeLocation, pipeRoute);
    [self addChild:water z:water_order tag:WaterTag];  
}
-(void) runWaterEffect:(NSInteger)x locationy:(NSInteger)y index1:(NSInteger)idxx index2:(NSInteger)idxy emmiterTag:(NSInteger)WaterTag{
    MLMyParticleSystem* water;
    
    if (!isWaterSoundOn) {
        waterSoundID = [[SimpleAudioEngine sharedEngine] playEffect:@"flowDown.caf" pitch:1.0 pan:0 gain:0.5 loop:true];
        isWaterSoundOn = YES;
    }
    

    if(pipeTerminalDir[idxx][idxy] == up){
        water = [MLMyParticleSystem particleWithFile:@"waterFlowUp2.plist"];
        water.position = CGPointMake(x+64, y+emmitOffset);
    }else if(pipeTerminalDir[idxx][idxy] == right){
        water = [MLMyParticleSystem particleWithFile:@"waterFlowRight2.plist"];
        water.position = CGPointMake(x+128+emmitOffset, y-64);        
    }else if(pipeTerminalDir[idxx][idxy] == down){
        water = [MLMyParticleSystem particleWithFile:@"waterFlowDown3.plist"];
        water.position = CGPointMake(x+64, y-128-emmitOffset);
    }else if(pipeTerminalDir[idxx][idxy] == left){
        water = [MLMyParticleSystem particleWithFile:@"waterFlowLeft2.plist"];
        water.position = CGPointMake(x-emmitOffset, y-64);
    }
    water.duration=-1;
    //water.totalParticles = 200;// Can change the flow of water
    //water.positionType=kCCPositionTypeGrouped;
    //checkPipe(pipeLocation, pipeRoute);
    [self addChild:water z:water_order tag:WaterTag];    
}

void checkPipe(int pipeLocation[][GRID_MAX_WIDTH],int pipeRoute[][GRID_MAX_WIDTH]){
    
    for (int i = 0; i < GRID_MAX_HEIGHT ; i++ )
    {
        for (int j = 0; j < GRID_MAX_WIDTH; j++)
        {
            pipeTerminalDir[i][j] = 0;
        }
    }
    
    // check route phrase
    for(int j = 0; j < GRID_MAX_WIDTH; j++ )
    {
        if (leakWaterLocation[j] == false) continue;
        if (pipeLocation[0][j]!=pipeA && pipeLocation[0][j]!=pipeC && pipeLocation[0][j]!= pipeD) {
            continue;
        }
        //CCLOG(@"QQQQQcc");
        
        if(pipeLocation[0][j] == pipeA){
            checkNext(0,j,down,j+1,pipeLocation,pipeRoute);
        }
        else if(pipeLocation[0][j] == pipeC){
            checkNext(0,j,right,j+1,pipeLocation,pipeRoute);
        }else{ // pipeD
            checkNext(0,j,left,j+1,pipeLocation,pipeRoute);
        }
        pipeRoute[0][j] = j+1;
        //CCLOG(@"j+1=%i",j+1);
    }
    /*
    for (int i = 0 ; i < GRID_MAX_HEIGHT; i++ )
    {
        for( int j = 0; j < GRID_MAX_WIDTH; j ++){
            CCLOG(@"%i    bcnh",pipeRoute[i][j]);
        }
        CCLOG(@"\n");
    }*/
}
-(void) setSoundState{
    if( MLGridFloorKickNum >3000 )
    {
        [soundState setVisible:true];
    }
}
-(void) checkSound{
    bool turnOff;
    for(int j=0; j<GRID_MAX_WIDTH; j++){
        for (int i=0; i<GRID_MAX_HEIGHT; i++){
            if (isWatterEmmiter[i][j])
                return;
        }
        if (isWatterEmmiterTop[j])
            return;
    
        if (leakWaterFlag[j])
            turnOff=NO;
    }

    if (turnOff) {
        CCLOG(@"close%i",waterSoundID);
        [[SimpleAudioEngine sharedEngine]stopEffect:waterSoundID];
        isWaterSoundOn = NO;
    }
    
 
}
/*
-(void) setleakWaterLocation:(NSInteger) x{
    leakWaterLocation[x] = true;
}*/
-(void) dealloc
{
	CCLOG(@"===========================================");
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);
    if (isWaterSoundOn) {
        [[SimpleAudioEngine sharedEngine]stopEffect:waterSoundID];
    }
	
    
	// always call [super dealloc] at the end of every dealloc method
	[super dealloc];
}

@end
